﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using FRL.DebtChased.Repository;
using FRL.DebtChased.Repository.ViewModels;
using FRL.DebtChased.Website;

namespace WebApplication.Finance
{

	/// <summary>
	/// Declaration of ErrorLog
	/// </summary>
	public partial class ErrorLog : System.Web.UI.Page
	{

		/////////////////////////////////////////////////////////////
		// Attributes

		private int? m_iDeleteErrorLogId = null;

		private bool m_bRebind = false;

		/////////////////////////////////////////////////////////////
		// Event handlers

		protected override void OnPreRender(EventArgs e)
		{

			// Call base-class function
			base.OnPreRender(e);

			// If rebinding...
			if (m_bRebind)
			{

				// Declare the model object
				ErrorLogModel m = null;

				// Declare an entity object
				using (DebtChasedEntities ent = new DebtChasedEntities())
				{

					// If deleting a record...
					if (m_iDeleteErrorLogId != null)
					{
						FRL.DebtChased.Repository.ErrorLog.DeleteErrorLog(ent, m_iDeleteErrorLogId.Value);
						m_iDeleteErrorLogId = null;
					}

					// Load the error-log model
					m = new ErrorLogModel(ent);

				}

				// Load the grid
				gridResult.DataSource = m.Elements;
				gridResult.DataBind();

				// Enable/disable controls
				butDeleteAll.Enabled = (m.Elements.Count > 0);

			}

		}

		protected void Page_Load(object sender, EventArgs e)
		{

			// If this is a postback...
			if (this.IsPostBack)
			{

			}
			else
			{

				// Rebind the grid
				m_bRebind = true;

				// Set panel colours
				MyApplication myApp = MyApplication.BindMyApplication();
				pnlResults.BackColor = myApp.PrimaryWebColor;
				pnlCommands.BackColor = myApp.PrimaryWebColor;

			}

		}

		protected void gridResult_RowCommand(object sender, GridViewCommandEventArgs e)
		{

			// Compare commands
			if (e.CommandName == "DeleteError")
			{

				// Check the grid view object
				GridView gridView = sender as GridView;
#if DEBUG
				System.Diagnostics.Trace.Assert(gridView == gridResult);
#endif // #if DEBUG

				// Get row index
				int iRow = int.Parse(e.CommandArgument.ToString());

				// Convert argument to id
				m_iDeleteErrorLogId = int.Parse(gridResult.DataKeys[iRow].Value.ToString());
#if DEBUG
				Debug.Assert(m_iDeleteErrorLogId != 0);
#endif // #if DEBUG

				// Rebind
				m_bRebind = true;

			}
			
		}

		protected void butDeleteAll_Click(object sender, EventArgs e)
		{

			// Delete all on pre-render
			m_iDeleteErrorLogId = -1;
			m_bRebind = true;

		}

	}

}